package cn.mhome.easy.spring.thrift.client.support;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransport;

public class ClientManager {

	/**
	 * 获取服务客户端
	 * @param serviceName
	 * @param transport
	 * @return
	 * @throws ClassNotFoundException
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static Object getClient(String serviceName,TTransport transport) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		// 协议要和服务端一致
		TProtocol protocol = new TBinaryProtocol(transport);
		
		String simpleName = serviceName.substring(serviceName.lastIndexOf(".") + 1, serviceName.length());
		TMultiplexedProtocol tmprotocol = 
				new TMultiplexedProtocol(protocol, simpleName);
		Class<?> clientClass = Class.forName(serviceName + "$Client");
		Class<?>[] cl = new Class[]{TProtocol.class};
		Constructor<?> con = clientClass.getDeclaredConstructor(cl);  
	    Object t = con.newInstance(tmprotocol); 
	    
	    return t;
	}
	
}
